<!-- 我的预约 -->
<template>
  <s-layout title="我的预约" class="booking-list-wrap">


    <!-- 预约列表 -->
    <view class="booking-content ss-p-x-20">
      <view v-if="state.pagination.list.length > 0" class="booking-list">
        <view
          v-for="item in state.pagination.list"
          :key="item.id"
          class="booking-item ss-m-b-24"
        >
          <view class="booking-card">
            <!-- 长方形卡片内容 -->
            <view class="card-content ss-flex ss-col-center">
              <!-- 左侧：教练信息 -->
              <view class="left-section ss-flex ss-col-center">
                <view class="coach-avatar">
                  <image
                    class="avatar-img"
                    :src="getCoachAvatar(item)"
                    mode="aspectFill"
                    @error="onAvatarError"
                  />
                </view>
                <view class="coach-info ss-m-l-16">
                  <view class="coach-name">{{ item.coachName || '教练' + item.coachId }}</view>
                  <view class="coach-title">专业驾驶教练</view>
                </view>
              </view>

              <!-- 中间：预约详情 -->
              <view class="middle-section ss-flex-1 ss-flex ss-row-center">
                <view class="detail-item ss-m-r-40">
                  <view class="detail-label">预约日期</view>
                  <view class="detail-value">{{ formatDate(item.bookingDate) }}</view>
                </view>

                <view class="detail-item">
                  <view class="detail-label">上课时间</view>
                  <view class="detail-value">{{ formatTimeRange(item.startTime, item.endTime) }}</view>
                </view>
              </view>

              <!-- 右侧：操作按钮 -->
              <view class="right-section" v-if="canCancel(item) || canRebook(item)">
                <button
                  v-if="canCancel(item)"
                  class="action-btn cancel-btn"
                  @tap="cancelBooking(item)"
                >
                  取消
                </button>
                <button
                  v-if="canRebook(item)"
                  class="action-btn rebook-btn"
                  @tap="rebookCoach(item)"
                >
                  再约
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <s-empty 
        v-else
        icon="/static/img/shop/empty/booking.png"
        text="暂无预约记录"
        showAction
        actionText="去预约"
        actionUrl="/pages/index/index"
      />
    </view>

    <!-- 加载更多 -->
    <uni-load-more
      v-if="state.pagination.list.length > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
        contentrefresh: '正在加载...',
        contentnomore: '没有更多了'
      }"
      @clickLoadMore="loadMore"
    />
  </s-layout>
</template>

<script setup>
  import { reactive, onMounted } from 'vue';
  import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import ScheduleBookingApi from '@/sheep/api/system/schedule-booking';
  import { resetPagination } from '@/sheep/helper/utils';

  const state = reactive({
    pagination: {
      list: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
    },
    loadStatus: 'more',
  });

  // 获取预约列表
  const getBookingList = async (page = 1, loading = true) => {
    state.loadStatus = 'loading';

    const params = {
      pageNo: page,
      pageSize: state.pagination.pageSize,
    };

    try {
      const { data } = await ScheduleBookingApi.getScheduleBookingPage(params);

      if (page === 1) {
        state.pagination.list = data.list || [];
      } else {
        state.pagination.list.push(...(data.list || []));
      }

      state.pagination.total = data.total || 0;
      state.pagination.pageNo = page;

      // 更新加载状态
      if (state.pagination.list.length >= state.pagination.total) {
        state.loadStatus = 'noMore';
      } else {
        state.loadStatus = 'more';
      }
    } catch (error) {
      console.error('获取预约列表失败:', error);
      state.loadStatus = 'more';

      uni.showToast({
        title: '获取预约列表失败',
        icon: 'none',
      });
    }
  };



  // 格式化日期
  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    const dayAfterTomorrow = new Date(today);
    dayAfterTomorrow.setDate(today.getDate() + 2);

    const month = date.getMonth() + 1;
    const day = date.getDate();
    const baseDate = `${month}月${day}日`;

    if (date.toDateString() === today.toDateString()) {
      return `${baseDate}(今天)`;
    } else if (date.toDateString() === tomorrow.toDateString()) {
      return `${baseDate}(明天)`;
    } else if (date.toDateString() === dayAfterTomorrow.toDateString()) {
      return `${baseDate}(后天)`;
    } else {
      // 为了保持视觉一致性，其他日期也加上空格占位
      return `${baseDate}　　　`;
    }
  };

  // 格式化时间范围
  const formatTimeRange = (startTime, endTime) => {
    // 检查参数是否存在
    if (!startTime || !endTime) {
      return '时间待定';
    }

    // 处理数组格式的时间 [12, 0] -> "12点"
    const formatSingleTime = (time) => {
      if (!time) {
        return '未知';
      }

      let hour, minute;

      // 如果是数组格式 [12, 0]
      if (Array.isArray(time)) {
        hour = time[0];
        minute = time[1] || 0;
      }
      // 如果是字符串格式 "12:00"
      else if (typeof time === 'string') {
        const parts = time.split(':');
        if (parts.length >= 2) {
          hour = parseInt(parts[0]);
          minute = parseInt(parts[1]);
        } else {
          return time; // 格式不对，直接返回原值
        }
      }
      // 其他格式
      else {
        return '未知';
      }

      // 格式化为中文显示
      return minute === 0 ? `${hour}点` : `${hour}:${minute.toString().padStart(2, '0')}`;
    };

    return `${formatSingleTime(startTime)}-${formatSingleTime(endTime)}`;
  };

  // 获取教练头像
  const getCoachAvatar = (item) => {
    if (item.coachImg) {
      return sheep.$url.cdn(item.coachImg);
    }
    return sheep.$url.static('/static/img/shop/default_avatar.png');
  };

  // 头像加载失败处理
  const onAvatarError = (e) => {
    e.target.src = sheep.$url.static('/static/img/shop/default_avatar.png');
  };



  // 获取状态样式类
  const getStatusClass = (item) => {
    const now = new Date();
    const bookingDateTime = new Date(`${item.bookingDate} ${item.endTime}`);
    
    if (bookingDateTime < now) {
      return 'status-completed';
    } else {
      return 'status-pending';
    }
  };

  // 获取状态文本
  const getStatusText = (item) => {
    const now = new Date();
    const bookingDateTime = new Date(`${item.bookingDate} ${item.endTime}`);
    
    if (bookingDateTime < now) {
      return '已完成';
    } else {
      return '待上课';
    }
  };

  // 是否可以取消
  const canCancel = (item) => {
    const now = new Date();
    const bookingDateTime = new Date(`${item.bookingDate} ${item.startTime}`);
    // 开始时间前2小时可以取消
    const cancelDeadline = new Date(bookingDateTime.getTime() - 2 * 60 * 60 * 1000);
    return now < cancelDeadline;
  };

  // 是否可以再次预约
  const canRebook = (item) => {
    const now = new Date();
    const bookingDateTime = new Date(`${item.bookingDate} ${item.endTime}`);
    return bookingDateTime < now; // 已完成的可以再次预约
  };

  // 取消预约
  const cancelBooking = (item) => {
    uni.showModal({
      title: '确认取消',
      content: '确定要取消这个预约吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await ScheduleBookingApi.deleteScheduleBooking(item.id);
            uni.showToast({
              title: '取消成功',
              icon: 'success',
            });
            getBookingList(1); // 刷新列表
          } catch (error) {
            uni.showToast({
              title: '取消失败',
              icon: 'none',
            });
          }
        }
      }
    });
  };

  // 再次预约
  const rebookCoach = (item) => {
    sheep.$router.go('/pages/coach/simple', { id: item.coachId });
  };

  // 加载更多
  const loadMore = () => {
    if (state.loadStatus === 'more') {
      getBookingList(state.pagination.pageNo + 1, false);
    }
  };

  // 页面加载
  onLoad(() => {
    getBookingList(1);
  });

  // 下拉刷新
  onPullDownRefresh(() => {
    resetPagination(state.pagination);
    getBookingList(1).finally(() => {
      uni.stopPullDownRefresh();
    });
  });

  // 上拉加载
  onReachBottom(() => {
    loadMore();
  });
</script>

<style lang="scss" scoped>
.booking-list-wrap {
  background: #f8fafb;
  min-height: 100vh;
}

// 预约内容区域
.booking-content {
  padding: 20rpx;
}

// 预约卡片
.booking-item {
  .booking-card {
    background: #ffffff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.04);
    border: 1rpx solid #f0f2f5;
    overflow: hidden;
    position: relative;
    transition: all 0.2s ease;

    &:active {
      transform: translateY(-2rpx);
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    }
  }
}



// 卡片内容
.card-content {
  padding: 24rpx;
}

// 卡片内容 - 横向布局
.card-content {
  padding: 32rpx 28rpx;
  display: flex;
  align-items: center;
  min-height: 120rpx;
}

// 左侧：教练信息
.left-section {
  display: flex;
  align-items: center;

  .coach-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 12rpx;
    overflow: hidden;
    flex-shrink: 0;

    .avatar-img {
      width: 100%;
      height: 100%;
    }
  }

  .coach-info {
    .coach-name {
      font-size: 32rpx;
      font-weight: 600;
      color: #262626;
      margin-bottom: 6rpx;
    }

    .coach-title {
      font-size: 26rpx;
      color: #8c8c8c;
    }
  }
}

// 中间：预约详情
.middle-section {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;

  .detail-item {
    text-align: center;

    .detail-label {
      font-size: 24rpx;
      color: #8c8c8c;
      margin-bottom: 8rpx;
    }

    .detail-value {
      font-size: 30rpx;
      color: #262626;
      font-weight: 500;
    }
  }
}

// 右侧：操作按钮
.right-section {
  display: flex;
  flex-direction: column;
  gap: 12rpx;

  .action-btn {
    width: 120rpx;
    height: 56rpx;
    border-radius: 12rpx;
    border: none;
    font-size: 26rpx;
    font-weight: 500;
    transition: all 0.2s ease;

    &.cancel-btn {
      background: #fff2f0;
      color: #ff4d4f;
      border: 1rpx solid #ffccc7;

      &:active {
        background: #ffebe8;
      }
    }

    &.rebook-btn {
      background: #1890ff;
      color: #ffffff;

      &:active {
        background: #096dd9;
      }
    }
  }
}
</style>
